import * as PIXI from 'pixi.js'
import { wheelBottom, cardClick, mousedownBottom } from '@renderer/utils/events'
import consume from './consume'
import name from './name'
import figure from './figure'
import ability from './ability'
import category from './category'
import series from './series'
import type from './type'
import { setData, setCardInfo } from '@renderer/store/modules/usePixiStore'
import useMagic from '@renderer/store/modules/useMagicStore'

// 卡牌参数
const CParams = {
  resolution: useMagic().PICTURE_BASE_SIZE, //卡图分辨率
  frontWidth: 353, //外框宽度
  insideWidth: useMagic().PICTURE_SCOPE, //内框宽度
  frontHeight: 506, //外框高度
  insideHeight: 490, //内框高度
  containerWidth: 295, //卡图宽度
  left: 30, //牌面左边距
  right: 27, //牌面右边距
  top: 23.5, //牌面顶部边距
  width: useMagic().PICTURE_BASE_SIZE - 30 - 27, //牌面宽度
}
export default async (data: Wx.Card.Data): Promise<PIXI.Container<PIXI.ContainerChild>> => {
  const assets = await PIXI.Assets.load<PIXI.Texture>('card_' + data.id) // 资源加载
  const container = new PIXI.Container()
  // 卡牌外框
  const typeSprite = await type(data)
  // 卡图
  const sprite = new PIXI.Sprite(assets)
  sprite.anchor.set(0.5)
  if (data.isDiy) {
    sprite.scale.set(data.transform.scale * useMagic().PICTURE_SCALE_COEFFICIENT)
    sprite.position.set(data.transform.x, data.transform.y - (506 / 2) * (1 - useMagic().PICTURE_SCALE_COEFFICIENT) + CParams.top)
  } else {
    sprite.scale.set(useMagic().PICTURE_SCALE_COEFFICIENT)
    sprite.position.set(0, -(506 / 2) * (1 - useMagic().PICTURE_SCALE_COEFFICIENT) + CParams.top)
  }

  // 蒙版
  const mask = new PIXI.Graphics()
  mask.rect(-typeSprite.width / 2, -typeSprite.height / 2, typeSprite.width, typeSprite.height).fill({
    color: 0x000000,
  })
  mask.scale.set(0.82, 0.92)
  sprite.mask = mask

  // 系列与稀有度
  const seriesSprite = await series(data)
  // 属性(费用)
  const consumeContainer = await consume(data)
  // 卡名容器
  const textContainer = await name(data)
  // 能力
  const abilityContainer = await ability(data)
  // 类别
  const categorySprite = await category(data)
  // 设置缩放和位置
  // 组装
  container.addChild(sprite) //卡图
  container.addChild(consumeContainer) // 属性(费用)
  container.addChild(textContainer) // 卡名
  container.addChild(seriesSprite) // 系列与稀有度
  container.addChild(typeSprite) // 外框
  container.addChild(categorySprite) // 类别
  container.addChild(abilityContainer) // 能力
  if (data.type === '生灵') {
    // 攻血
    const figureContainer = figure(data)
    container.addChild(figureContainer) // 身材
  }
  container.addChild(mask)
  // 添加卡牌事件
  wheelBottom.whiteAdd(container)
  mousedownBottom.whiteAdd(container)
  cardClick.whiteAdd(container)
  // 设置卡牌信息
  data._assets = assets
  data._container = container
  // 存入pixi仓库
  setData(container.uid, data)
  setCardInfo(data.id, container.uid)
  return container
}
